package com.lyn.advance;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;
import com.lyn.advance.adapters.AdvanceAdapter;
import com.lyn.advance.fragments.PictureFragment;
import com.lyn.advance.fragments.VideoFragment;
import com.lyn.advance.interfaces.Advance;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 广告轮播
 *
 * @author longyn 2023/6/29
 * @version 1.0.0
 */
public class AdvanceFragment extends Fragment implements Advance {

    public static final String TAG = "AdvanceFragment";

    private final Handler handler = new Handler(Looper.getMainLooper());

    private final List<AdvanceListener> advanceListenerList = new ArrayList<>();

    private ViewPager2 advanceViewpager2;

    private AdvanceAdapter adapter;

    private String path;

    private Type type = Type.PICTURE;

    private long intervalTime;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        adapter = new AdvanceAdapter(getParentFragmentManager(), getLifecycle());
        loadData();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_advance,
                container, false);
        advanceViewpager2 = view.findViewById(R.id.advance_viewpager2);
        advanceViewpager2.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
        advanceViewpager2.setAdapter(adapter);
        advanceViewpager2.setOffscreenPageLimit(100);
        advanceViewpager2.setUserInputEnabled(false);
        return view;
    }

    /**
     * 当前item
     */
    private int currentItem;

    /**
     * 图片完成监听器
     */
    private final AdvanceListener pictureAdvanceListener = new AdvanceListener() {
        @Override
        public void onCompletion(Type type) {
            handler.post(() -> {
                currentItem += 1;
                if (currentItem >= adapter.getItemCount()) {
                    currentItem = 0;
                }
                advanceViewpager2.setCurrentItem(currentItem, currentItem != 0);
            });
        }
    };

    /**
     * 视频播放完成监听器
     */
    private final AdvanceListener videoAdvanceListener = new AdvanceListener() {
        @Override
        public void onCompletion(Type type) {
            handler.post(() -> {
                currentItem += 1;
                if (currentItem >= adapter.getItemCount()) {
                    currentItem = 0;
                }
                if (adapter.getItemCount() == 1) {
                    Fragment fragment = getChildFragmentManager().findFragmentById(currentItem);
                    if (fragment != null) {
                        fragment.onResume();
                    }
                    return;
                }
                advanceViewpager2.setCurrentItem(currentItem, currentItem != 0);
            });
        }
    };

    @Override
    public void init(String path) {
        this.path = path;
    }

    @Override
    public void setType(Type type) {
        this.type = type;
    }

    @Override
    public void setAdvanceListener(AdvanceListener advanceListener) {
        this.advanceListenerList.add(advanceListener);
    }

    @Override
    public void removeAdvanceListener(AdvanceListener advanceListener) {
        for (AdvanceListener ad : advanceListenerList) {
            advanceListenerList.remove(ad);
        }
    }

    @Override
    public void setIntervalTime(long intervalTime) {
        this.intervalTime = intervalTime;
    }

    /**
     * 加载数据
     */
    public void loadData() {
        if (adapter == null) return;
        List<String> list = getAllAdvanceFile(new File(path));
        if (list.isEmpty()) return;
        adapter.clear();
        for (String path : list) {
            boolean b = path.endsWith(".jpg")
                    || path.endsWith(".png")
                    || path.endsWith(".JPG")
                    || path.endsWith(".PNG");
            if (this.type == Type.PICTURE) {
                if (b) {
                    AdvanceAdapter.AdvanceItem advanceItem = new AdvanceAdapter.AdvanceItem();
                    advanceItem.setPath(path);
                    advanceItem.setFragmentClass(PictureFragment.class);
                    advanceItem.setIntervalTime(this.intervalTime);
                    advanceItem.setAdvanceListener(pictureAdvanceListener);
                    adapter.addFragment(advanceItem);
                }
                continue;
            }
            if (this.type == Type.VIDEO) {
                if (path.endsWith(".mp4")
                        || path.endsWith(".MP4")) {
                    if (isDetached()) return;
                    AdvanceAdapter.AdvanceItem advanceItem = new AdvanceAdapter.AdvanceItem();
                    advanceItem.setPath(path);
                    advanceItem.setFragmentClass(VideoFragment.class);
                    advanceItem.setIntervalTime(this.intervalTime);
                    advanceItem.setAdvanceListener(videoAdvanceListener);
                    adapter.addFragment(advanceItem);
                }
            }
        }
    }

    /**
     * 获取文件夹下所有广告文件路径
     */
    private List<String> getAllAdvanceFile(File file) {
        List<String> pathList = new ArrayList<>();
        File[] files = file.listFiles();
        if (files != null) {
            for (File f : files) {
                if (f.isDirectory()) {
                    return getAllAdvanceFile(f);
                } else {
                    if (f.getName().endsWith(".jpg")
                            || f.getName().endsWith(".png")
                            || f.getName().endsWith(".JPG")
                            || f.getName().endsWith(".PNG")
                            || f.getName().endsWith(".mp4")
                            || f.getName().endsWith(".MP4")) {
                        pathList.add(f.getAbsolutePath());
                    }
                }
            }
        }
        return pathList;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            adapter.clear();
        }catch (Throwable e){
            e.printStackTrace();
        }
    }
}
